import axios from "axios";

export function checkStates(response) {
    console.log(response);
    if (response.response.status === 401 || response.response.status === 403) {
        if (process.env.NODE_ENV === 'development') {
            console.log("no login")
        }
        localStorage.removeItem('currentUser');
        location.reload();
    }
}

export function getP(url, config, then, onError) {
    if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
    }
    axios.get(url, config).then(then).catch((response) => {
        checkStates(response);
        if (onError) {
            onError(response);
        }
    })
}

export function getPK(url, keyAgreeResult, then, onError) {
    getP(url, {
        headers: {
            publicKey: keyAgreeResult.publicKey
        }
    }, then, onError)
}


export function get(url, then, onError) {
    if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
    }
    axios.get(url).then(then).catch((response) => {
        checkStates(response);
        if (onError) {
            onError(response);
        }

    })
}

export function post(url, data, then, onError) {
    if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
    }
    axios.post(url, data).then(then).catch((response) => {
        checkStates(response);
        if (onError) {
            onError(response);
        }
    })

}

export function postP(url, data, config, then, onError) {
    if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
    }
    axios.post(url, data, config).then(then).catch((response) => {
        checkStates(response);
        if (onError) {
            onError(response);
        }
    })

}

export function postPK(url, data, keyAgreeResult, then, onError) {
    postP(url, data, {
        headers: {
            publicKey: keyAgreeResult.publicKey
        }
    }, then, onError)
}
